package cc.catface.app_kotlin_demo

/**
 * 更多语言结构
 */
fun main() {

    //is、!is
    val obj = Any()
    println(obj is String)
    println(obj !is String)

    //智能转换-不需显式强转(可用于is、||、while等)
    if (obj is String) println("length:${obj.length}")
    if (obj !is MutableList<*> || obj.contains("akali")) {
    }

    //?可为空
    val sX = null
    val sY: String? = sX as? String

    //?可为空
    val sZ: String? = null

    //?.安全调用-sZ为空时返回null
    println("sZ's length:${sZ?.length}")

    //!!值为空时抛异常
    //println("sZ's length:${sZ!!.length}")


    /* 几个函数
        对⼀个⾮空（non-null）对象执⾏ lambda 表达式：let
        将表达式作为变量引⼊为局部作⽤域中：let
        对象配置：apply
        对象配置并且计算结果：run
        在需要表达式的地⽅运⾏语句：⾮扩展的 run
        附加效果：also
        ⼀个对象的⼀组函数调⽤：with
     */
    //let[sentence(...x).let { x -> {}}]
    val letNumbers = listOf("one", "two", "three", "four", "five")
    //输出长度大于3的值
    println(letNumbers.map { it.length }.filter { it > 3 })
    letNumbers.map { it.length }.filter { it > 3 }.let { println(it) }//使用let且可用it作为lambda参数
    letNumbers.map { it.length }.filter { it > 3 }.let { num -> println(num) }//使用自定义参数名代替默认的it
    letNumbers.map { it.length }.filter { it > 3 }.let(::println)//参数为单个函数时可用::代替lambda
    //let适合用于非空值的执行代码块(可用安全操作符?声明该值)
    val letStr: String? = null//"hello"
    letStr?.let {//添加?安全操作符
        println("letStr is $it")
        println("letStr length is ${it.length}")
    }
    //with[对于这个对象执行以下操作]
    val withNumbers = listOf("one", "two", "three", "four", "five")
    val w1 = with(withNumbers) {
        println("w1 withNumbers:$this")
        println("w1 withNumbers size:${this.size}")
        println("w1 withNumbers size:${size}")
    }
    println(w1)//Kotlin.Unit
    val w2 = with(withNumbers) {
        println("w2 withNumbers")
        "w2 withNumbers, $this, $size"//w2==该str值
    }
    println(w2)
    //also[并且用该对象执行以下操作]
    val alsoNumbers = mutableListOf("one")
    alsoNumbers.also {
        it.add("two")
        it.add("three")
        it.add("four")
        println("alsoNumbers:$it")
    }
    println("alsoNumbers after also{}:$alsoNumbers")


}

class LanguageStructureSupply {
}